package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dao.DishMapper;
import com.itheima.dao.SetmealMapper;
import com.itheima.exception.BussinessException;
import com.itheima.pojo.Category;
import com.itheima.dao.CategoryMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Pageparam;
import com.itheima.pojo.Setmeal;
import com.itheima.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.awt.CustomCursor;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-11-28
 */
@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private CategoryMapper dao;
    @Autowired
    private DishMapper dao1;
    @Autowired
    private SetmealMapper dao2;

    @Override
    public int add(Category ca) {
        return dao.insert(ca);

    }

    @Override
    public int delete(Long id) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategory_id, id);
        Integer count = dao1.selectCount(qw);
        if (count>0) {
            throw new BussinessException("该分类关联了菜品，无法删除！");
            }

        LambdaQueryWrapper<Setmeal> lw = new LambdaQueryWrapper<>();
        lw.eq(Setmeal::getCategory_id, id);
        Integer count1 = dao2.selectCount(lw);
        if (count>0) {
            throw new BussinessException("该分类关联了套餐，无法删除！");
        }
        int i = dao.deleteById(id);
        return i;
    }

    @Override
    public int updateCategory(Category ca) {
        return dao.updateById(ca);
    }

    @Override
    public List<Category> select(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType, type);
        List<Category> list = dao.selectList(wrapper);
        return list;
    }

    @Override
    public Page findAllCategory(Pageparam page) {
        Page<Category> condition = new Page<>(page.getPage(), page.getPageSize());
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByAsc(Category::getSort);
        Page<Category> result = dao.selectPage(condition, qw);


        return result;
    }
}
